/*
MainDelegate.m - Copyright (c) 1992 NeXT Computer, Inc.

You may freely copy, distribute and reuse the code in this example.
NeXT Computer, Inc. disclaims any warranty of any kind, expressed or implied, 
as to its fitness for any particular use.
*/

#import "MainDelegate.h"
#import "ListController.h"
#import "CalendarView.h"
#import "DailyBread.h"

#import <indexing/indexing.h>

@implementation MainDelegate

- appDidInit:sender
{
    char		oldDirectory[1 + MAXPATHLEN];
    unsigned            handle;
    id                  storeFile;

    strcpy(appDirectory, getenv("HOME"));
    chdir(appDirectory);
    getwd(oldDirectory);
    windows = [[HashTable alloc] initKeyDesc:"*"];
    if ((mainStore = [[IXRecordManager alloc] initFromName:"ToDoList"
	inFile:"ToDoList.store"forWriting:YES])) {
    /* just open the ToDoList */
	[mainStore getBlock:&handle andStore:&storeFile];
    } else {
    /* create ToDoList */
	mainStore = [[IXRecordManager alloc] initWithName:"ToDoList"
		     inFile:"ToDoList.store"];
	[mainStore getBlock:&handle andStore:&storeFile];
	[mainStore addAttributeNamed:"TheDate" forSelector:@selector(theDate)];
 	[mainStore addAttributeNamed:"TheContent" forSelector:@selector(stringValue)];
	[mainStore setParser:[[IXAttributeParser alloc] init]
	    forAttributeNamed:"TheContent"];

	// the following two lines enable transactions
	[storeFile startTransaction];
	[storeFile commitTransaction];
    }

    getwd(appDirectory);
    chdir(oldDirectory);
    [self dateDidChange:calView];
    return self;
}

- recordManager
{
    return mainStore;
}

- appWillTerminate:sender
{
    id                  storeFile;
    unsigned            handle;

    [mainStore getBlock:&handle andStore:&storeFile];

    // this is *VERY* important to be sure the changes make it into the store. 
    [storeFile commitTransaction];

    [mainStore free];
    return self;
}

- popChooser:sender
{
    [chooser makeKeyAndOrderFront:sender];
    return self;
}

- dateDidChange:sender
{
    char	*theDate;
    char	*theBlank;
    id		newOne;

    theDate = NXCopyStringBuffer([sender stringValue]);
    if (theBlank = strchr(theDate, ' ')) *theBlank = '\0';
    if ([windows isKey:theDate] == YES) {
    	/* pull it out of the list and pop forward. */
	[(ListController *)[windows valueForKey:theDate] orderUp:self];
    } else {
	newOne = [[ListController alloc] initForDateString:theDate andRecordManager:mainStore];
	[windows insertKey:theDate value:newOne];
    }

    return self;
}

- windowWillDisappear:sender
{
    char	theDate[64]; // date should always be less than 64 bytes
    char	*theBlank;

    strcpy(theDate, [sender theDate]);
    if (theBlank = strchr(theDate, ' ')) *theBlank = '\0';
    if ([windows isKey:theDate] == YES)
	[windows removeKey:theDate];

    return self;
}

@end
